package com.situ.web.servlet;

import com.situ.web.pojo.Banji;
import com.situ.web.pojo.Student;
import com.situ.web.pojo.vo.StudentBanjiVO;
import com.situ.web.service.IBanjiService;
import com.situ.web.service.impl.BanjiServiceImpl;
import com.situ.web.util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 浏览器可以访问jsp，tomcat把这个jsp页面返回给浏览器
 * 浏览器还可以访问servlet
 * http://localhost:8080/student_list.jsp
 * http://localhost:8080/student
 */
//@WebServlet("student") //servlet映射中的<url pattern>[student]无效
//@WebServlet("/student")
public class StudentServlet extends HttpServlet {
    private IBanjiService banjiService = new BanjiServiceImpl();

    //访问servlet时候默认访问service方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("StudentServlet.service");
        //解决post乱码问题
        //req.setCharacterEncoding("UTF-8");
        //http://localhost:8080/student
        //http://localhost:8080/deleteStudent?id=12

        //默认所有和学生相关的请求都访问/student这个servlet，根据参数method的值是多少区分增删改查操作
        //http://localhost:8080/student
        //http://localhost:8080/student?mthod=selectAll
        //http://localhost:8080/student?mthod=deleteById&id=12
        //http://localhost:8080/student?mthod=add
        String method = req.getParameter("method");
        if (method == null || method.equals("")) {
            method = "selectAll";
        }
        switch (method) {
            case "selectAll":
                selectAll(req, resp);
                break;
            case "deleteById":
                deleteById(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "toAdd":
                toAdd(req, resp);
                break;
            case "toUpdate":
                toUpdate(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("StudentServlet.update");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        System.out.println("id: " + id);
        System.out.println("name: " + name);
        System.out.println("age: " + age);
        System.out.println("gender: " + gender);

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "UPDATE student SET name=?,age=?,gender=? WHERE id=?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, name);
            preparedStatement.setInt(2, Integer.parseInt(age));
            preparedStatement.setString(3, gender);
            preparedStatement.setInt(4, Integer.parseInt(id));
            System.out.println(preparedStatement);
            int count = preparedStatement.executeUpdate();
            System.out.println("count: " + count);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, preparedStatement, null);
        }

        resp.sendRedirect("/student");
    }

    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("StudentServlet.toUpdate");
        ///student?method=toUpdate&id=1
        String id = req.getParameter("id");

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Student student = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "SELECT id,name,age,gender FROM student WHERE id=?";
            //预编译的Statement
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, Integer.parseInt(id));
            System.out.println(preparedStatement);
            resultSet  = preparedStatement.executeQuery();
            while (resultSet.next()) {//判断下一个有没有，如果没有返回false，如果有返回true，并且指向这一行
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                student = new Student(Integer.parseInt(id), name, age, gender);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, preparedStatement, resultSet);
        }

        req.setAttribute("student", student);
        req.getRequestDispatcher("/student_update.jsp").forward(req, resp);
    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("StudentServlet.selectStudentAddPage");
        List<Banji> list = banjiService.selectAll();
        req.setAttribute("list", list);
        req.getRequestDispatcher("/student_add2.jsp").forward(req, resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("StudentServlet.add");
        //不管get还是post请求传递参数，本质上都是参数
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        String banjiId = req.getParameter("banjiId");
        System.out.println("name: " + name);
        System.out.println("age: " + age);
        System.out.println("gender: " + gender);
        System.out.println("banjiId: " + banjiId);

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "INSERT INTO student(name,age,gender,banji_id) VALUES (?,?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, name);
            preparedStatement.setInt(2, Integer.parseInt(age));
            preparedStatement.setString(3, gender);
            preparedStatement.setObject(4, banjiId.equals("") ? null : Integer.parseInt(banjiId));
            System.out.println(preparedStatement);
            int count = preparedStatement.executeUpdate();
            System.out.println("count: " + count);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, preparedStatement, null);
        }

        resp.sendRedirect("/student");
    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("StudentServlet.deleteById");
        String id = req.getParameter("id");
        System.out.println("id: " + id);
        //int i = Integer.parseInt(id);

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "DELETE FROM student WHERE id=?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, Integer.parseInt(id));
            System.out.println(preparedStatement);
            int count = preparedStatement.executeUpdate();
            System.out.println("count: " + count);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, preparedStatement, null);
        }

        //重定向到查找所有  /student
        resp.sendRedirect("/student?method=selectAll");
    }

    private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<StudentBanjiVO> list = new ArrayList<>();
        try {
            connection = JDBCUtil.getConnection();
            String sql = "SELECT s.id,s.`name`,s.age,s.gender,b.`name` AS banjiName\n" +
                    "FROM student AS s LEFT JOIN banji AS b\n" +
                    "ON s.banji_id=b.id";
            //预编译的Statement
            preparedStatement = connection.prepareStatement(sql);
            resultSet  = preparedStatement.executeQuery();
            while (resultSet.next()) {//判断下一个有没有，如果没有返回false，如果有返回true，并且指向这一行
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                String banjiName = resultSet.getString("banjiName");
                StudentBanjiVO studentBanjiVO = new StudentBanjiVO(id, name, age, gender, banjiName);
                list.add(studentBanjiVO);
            }
            for (StudentBanjiVO studentBanjiVO : list) {
                System.out.println(studentBanjiVO);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, preparedStatement, resultSet);
        }

        //把list集合交给student_list.jsp进行展示
        //把list放到一块内存里面
        req.setAttribute("list", list);
        //跳转到student_list.jsp
        req.getRequestDispatcher("student_list.jsp").forward(req, resp);
    }
}
